import 'dart:async';

import 'package:flutter/material.dart';
import '../utils/adapt.dart';
import '../utils/request.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../event_bus.dart';
import 'package:provider/provider.dart';
import '../provider/playAudioList.dart';
import '../provider/audioProgress.dart';
import '../provider/currentRoute.dart';
import 'package:audio_video_progress_bar/audio_video_progress_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class AudioPlayer extends StatefulWidget {
  var arguments;
  AudioPlayer({Key? key, this.arguments}) : super(key: key);

  @override
  _AudioPlayerState createState() =>
      _AudioPlayerState(arguments: this.arguments);
}

class _AudioPlayerState extends State<AudioPlayer> {
  var arguments;
  _AudioPlayerState({this.arguments});
  bool _isPlaying = false;
  bool _currentState = false;
  var _topImg = '';
  var _name = '';
  var _lyrics = [];
  bool _noPrev = false;
  bool _noNext = false;
  var currentRoute;
  var timeArr = [];

  void _getLyrics(id) async {
    EasyLoading.show(status: 'loading...');
    var res = await getHttp('/lyric?id=$id');
    EasyLoading.dismiss();
    if (res['lrc'] != null) {
      var a = res['lrc']['lyric'];
      var reg = new RegExp(r"\n");
      var arr = a.split(reg);
      var arrLyric = [];
      var _timeArr = [];
      arr.forEach((item) {
        var arr2 = item.split(']');
        if (arr2.length < 2) return;
        arrLyric.add(arr2[1]);
        _timeArr.add(_changeTime(arr2[0]));
      });
      this.setState(() {
        _lyrics = arrLyric;
        timeArr = _timeArr;
      });
    }
  }

  int _changeTime(p) {
    var _t = 0;
    var _cur = "$p".substring(1, 6);
    var _m = int.parse("$_cur".substring(0, 2));
    var _s = int.parse("$_cur".substring(3));
    var _total = _m * 60 + _s;
    return _total;
  }

  void _getUrl(id) async {
    var res = await getHttp('/song/url?id=$id');
    var data = res['data'][0];
    if (data['url'] == null) {
      EasyLoading.showError('该歌曲不可用！');
      const timeout = const Duration(seconds: 2);
      Timer(timeout, () {
        EasyLoading.dismiss();
        Navigator.pop(context);
      });
    } else {
      var url = data['url'].replaceAll('http', 'https');

      eventbus.fire(new setAudioUrl(url));
      this.setState(() {
        _isPlaying = true;
        _currentState = true;
      });
    }
  }

  void _playNext() {
    Navigator.pushReplacementNamed(context, "/audioplayer", arguments: {});
  }

  void _playPrev() {
    Navigator.pushReplacementNamed(context, "/audioplayer", arguments: {});
  }

  void initAudio(index, list) {
    if (_isPlaying) {
      return;
    }
    this.setState(() {
      _noNext = true;
      _noPrev = true;
    });
    var _duration = Duration(seconds: 5);
    Timer(_duration, () {
      this.setState(() {
        _noNext = list.length == 1 ? true : false;
        _noPrev = false;
      });
    });
    var id = list[index]['id'];
    this.setState(() {
      _topImg = list[index]['picUrl'];
      _name = list[index]['name'];
    });
    _getUrl(id);
    _getLyrics(id);
  }

  ScrollController _controller = new ScrollController();
  void _timeChange(currentTime) {
    int _index = this.timeArr.indexOf(currentTime);
    if (_index != -1) {
      _controller.animateTo(_index * 30,
          duration: Duration(milliseconds: 200), curve: Curves.linear);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    eventbus.on<progressChange>().listen((event) {
      _timeChange(event.currentTime);
    });
  }

  @override
  void dispose() {
    super.dispose();
    currentRoute.setValue(false);
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var playAudioList = Provider.of<PlayAudioList>(context);
    var index = playAudioList.getCurrentIndex;
    var length = playAudioList.getAudioList.length;
    var audioProgress = Provider.of<AudioProgress>(context);
    this.currentRoute = Provider.of<atPlayRoute>(context);
    currentRoute.setValue(true);
    if (index == 0) {
      this.setState(() {
        _noPrev = true;
      });
    } else if (index == length - 1) {
      this.setState(() {
        _noNext = true;
      });
    }
    this.initAudio(playAudioList.getCurrentIndex, playAudioList.getAudioList);
    return Scaffold(
      body: Stack(
        children: [
          CustomScrollView(
            slivers: <Widget>[
              SliverAppBar(
                pinned: true, // appbar是否固定在顶部
                floating: true, // 下滑时top立马跟随
                snap: true,
                expandedHeight:
                    _isPlaying == true ? Adapt.px(666) : Adapt.px(1),
                flexibleSpace: FlexibleSpaceBar(
                  title: Text(
                    "$_name",
                    style: TextStyle(
                      fontSize: Adapt.px(30),
                    ),
                  ),
                  background: Image.network(
                    _topImg + '?param=750y666',
                    fit: BoxFit.fill,
                  ),
                ),
              ),
              SliverToBoxAdapter(
                child: Container(
                  height: 300,
                  child: ListWheelScrollView(
                    controller: _controller,
                    itemExtent: 30,
                    useMagnifier: true,
                    overAndUnderCenterOpacity: 0.2,
                    magnification: 1.5,
                    children: List.generate(
                      _lyrics.length,
                      (index) {
                        return Container(
                          child: Center(
                              child: Text(
                            "${_lyrics[index]}",
                            style: TextStyle(
                              fontSize: Adapt.px(28),
                            ),
                            maxLines: 1,
                          )),
                        );
                      },
                    ),
                  ),
                ),
              ),
              SliverToBoxAdapter(
                child: Container(
                  height: 59,
                ),
              ),
            ],
          ),
          Positioned(
            bottom: Adapt.px(-1),
            left: 0,
            child: Container(
                height: Adapt.px(105),
                width: Adapt.px(750),
                color: Colors.white,
                child: Row(
                  children: [
                    Container(
                      width: Adapt.px(300),
                      height: Adapt.px(105),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          InkWell(
                            onTap: () {
                              var index = playAudioList.getCurrentIndex;
                              if (index == 0) {
                                print("已经是第一首歌啦");
                              } else {
                                if (_noPrev) {
                                  return;
                                }
                                playAudioList.setCurrentIndex(index - 1);
                                _playPrev();
                              }
                            },
                            child: Icon(
                              Icons.skip_previous,
                              size: Adapt.px(72),
                              color: _noPrev ? Colors.grey : Colors.blue,
                            ),
                          ),
                          IconButton(
                            onPressed: () {
                              var _state =
                                  playAudioList.getCurrentState; // 获取全局状态里的播放状态

                              eventbus.fire(
                                  new changeAudioState(_state)); // 广播改变状态的事件
                              this.setState(() {
                                _currentState = _state;
                              });
                            },
                            icon: Icon(
                              _currentState
                                  ? Icons.pause
                                  : Icons.play_circle_fill,
                              size: Adapt.px(62),
                              color: Colors.blue,
                            ),
                          ),
                          InkWell(
                            onTap: () {
                              var index = playAudioList.getCurrentIndex;
                              var length = playAudioList.getAudioList.length;
                              if (index == length - 1) {
                                print("已经是最后一首歌啦");
                              } else {
                                if (_noNext) {
                                  return;
                                }
                                playAudioList.setCurrentIndex(index + 1);
                                _playNext();
                              }
                            },
                            child: Icon(
                              Icons.skip_next,
                              size: Adapt.px(72),
                              color: _noNext ? Colors.grey : Colors.blue,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: Adapt.px(450),
                      height: Adapt.px(105),
                      padding: EdgeInsets.symmetric(
                        vertical: Adapt.px(20),
                        horizontal: Adapt.px(30),
                      ),
                      color: Colors.blue[100],
                      child: ProgressBar(
                        progress: Duration(
                            milliseconds: audioProgress.getCurrentTime),
                        buffered: Duration(milliseconds: 0),
                        total:
                            Duration(milliseconds: audioProgress.getTotalTime),
                        onSeek: (duration) {
                          // print('User selected a new time: $duration');
                          eventbus.fire(new setAudioSeek(duration));
                        },
                      ),
                    ),
                  ],
                )),
          )
        ],
      ),
    );
  }
}
